#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include "Socket.hpp"
#include "Log.hpp"

static const int defaultport = 8080;

struct ThreadData {
    int sockfd;
};

class HttpServer {
public:
    HttpServer(uint16_t port = defaultport) 
        :port_(port) {}

    bool Start() {
        listensock_.Socket();
        listensock_.Bind(port_);
        listensock_.Listen();

        for(;;) {
            std::string clientip;
            uint16_t clientport;
            int sockfd = listensock_.Accepet(&clientip, &clientport);
            lg(Info, "get a new connect, sockfd:%d", sockfd);
            pthread_t tid;
            ThreadData* td = new ThreadData;
            td->sockfd = sockfd;
            pthread_create(&tid, nullptr, ThreadRun, td);
        }
    }

    static void* ThreadRun(void* args) {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        
        char buffer[10240];
        ssize_t n = recv(td->sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0) {
            buffer[n] = 0;
            std::cout << "Received HTTP request:\n" << buffer << std::endl;
            
            // 构造一个合法的 HTTP 响应
            const char* response = 
                "HTTP/1.1 200 OK\r\n"
                "Content-Type: text/html\r\n"
                "Content-Length: 48\r\n"
                "Connection: close\r\n"
                "\r\n"
                "<html><body><h1>Hello from HttpServer!</h1></body></html>";
            
            send(td->sockfd, response, strlen(response), 0);
        } else {
            std::cout << "recv failed or connection closed" << std::endl;
        }
        
        close(td->sockfd);
        delete td;
        return nullptr;
    }



    ~HttpServer() {}
private:
    Sock listensock_;
    uint16_t port_;
};

